package com.kk.interceptor;

import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * @author: kevin
 * @data: 2018-08-20 11:27
 * @desc:
 */
@Log4j2
@ConfigurationProperties(prefix = "spring.cross")
//TODO 全局日志文件
public class CrossInterceptor implements HandlerInterceptor {
    private static List<String> allowHosts;

    @Value("${spring.cross.setAllowHosts}")
    private String setAllowHosts;

    //配置允许跨域的域名
    public void setAllowHosts(String allow) {
        if ("true".equals(setAllowHosts) && allow != null) {
            allowHosts = Arrays.asList(allow.split(","));
        }
    }

    /**
     * return false: 前端只能接受到空消息，相当于请求中断，不返回任何消息
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String origin = request.getHeader(HttpHeaders.ORIGIN);
        System.out.println(origin);
        if (origin != null) {
            if ("true".equals(setAllowHosts)) {
                if (!allowHosts.contains(origin)) {
                    log.error("不允许访问的host", origin);
                    return false;
                }
            } else {
                log.info("不限制host跨域");
            }
            response.setHeader("Access-Control-Allow-Origin", origin);    //设置Origin后，将接受不到Options请求之后的请求
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, HEAD");
            response.setHeader("Access-Control-Allow-Headers", "Content-Type, X-Access-Token, token");//request.getHeader("Access-Control-Request-Headers")
            response.setHeader("Access-Control-Max-Age", "3600");

        } else {//不允许没有Origin的请求，例如postMan请求的接口origin为null，浏览器端请求是有Origin的
            log.error("origin为空");
            //TODO 判断是否为线上配置文件，如果是则return false(限制)，开发环境不限制，或者都不限制
//            return false;
        }
        return true;
    }
}
